using Lemon.BackgroundJobs.Abstractions;
using Lemon.BackgroundJobs.Abstractions.DelayQueues;
using Lemon.BackgroundJobs.Abstractions.PublishSubscribe;
using Lemon.BackgroundJobs.Abstractions.WorkQueues;
using Lemon.BackgroundJobs.RabbitMQ.DelayQueues;
using Lemon.BackgroundJobs.RabbitMQ.PublishSubscribe;
using Lemon.BackgroundJobs.RabbitMQ.WorkQueues;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace Lemon.BackgroundJobs.RabbitMQ;

public static class RabbitMQServiceCollectionExtensions
{
    /// <summary>
    /// 依赖注入使用RabbitMQ
    /// </summary>
    /// <param name="services"></param>
    public static IServiceCollection UseRabbitMQ(this IServiceCollection services)
    {
        services.AddTransient<IRabbitMQClient, RabbitMQClient>();
        services.AddTransient<IPublishSubscribe, PublishSubscribe.PublishSubscribe>();
        services.AddTransient<IWorkQueues, WorkQueues.WorkQueues>();
        services.AddTransient<IDelayQueues, DelayQueues.DelayQueues>();

        var configuration = services.BuildServiceProvider().GetService<IConfiguration>();

        var types = AppDomain.CurrentDomain.GetAssemblies()
            .SelectMany(a => a.GetTypes().Where(t => t.BaseType != null &&
                                                     (t.BaseType.Name == typeof(PublishSubscribeJob<>).Name
                                                     || t.BaseType.Name == typeof(WorkQueuesJob<>).Name
                                                     || t.BaseType.Name == typeof(DelayQueuesJob<>).Name)
            )).ToArray();
        foreach (var type in types)
        {
            services.AddTransient(type);
            var backgroundJob = services.BuildServiceProvider().GetService(type) as IBackgroundJob;
            backgroundJob?.Receive();
        }
        return services;
    }
}